package main

import (
	"fmt"
	"sync"
	"time"
)

// 日志条目结构
type LogEntry struct {
	Time     time.Duration
	Producer string
	Channel  string
	Consumer string
}

// 全局变量
var (
	startTime time.Time
	logMutex  sync.Mutex
	logs      []LogEntry
)

// 记录日志函数
func logEvent(producer, channel, consumer string) {
	logMutex.Lock()
	defer logMutex.Unlock()

	elapsed := time.Since(startTime)
	logs = append(logs, LogEntry{
		Time:     elapsed,
		Producer: producer,
		Channel:  channel,
		Consumer: consumer,
	})
}

// 格式化channel状态
func formatChannel(buffer []int) string {
	if len(buffer) == 0 {
		return "[]"
	}
	result := "["
	for i, v := range buffer {
		if i > 0 {
			result += ","
		}
		result += fmt.Sprintf("%d", v)
	}
	result += "]"
	return result
}

// 模拟channel缓冲区
type ChannelBuffer struct {
	buffer []int
	mu     sync.Mutex
}

func (cb *ChannelBuffer) Add(value int) {
	cb.mu.Lock()
	defer cb.mu.Unlock()
	cb.buffer = append(cb.buffer, value)
}

func (cb *ChannelBuffer) Remove() int {
	cb.mu.Lock()
	defer cb.mu.Unlock()
	if len(cb.buffer) == 0 {
		return -1
	}
	value := cb.buffer[0]
	cb.buffer = cb.buffer[1:]
	return value
}

func (cb *ChannelBuffer) Status() string {
	cb.mu.Lock()
	defer cb.mu.Unlock()
	return formatChannel(cb.buffer)
}
func simpleTimeline() {
	fmt.Println("\n=== 简化版时间轴 ===")

	startTime := time.Now()
	ch := make(chan int, 5)
	channelState := make([]int, 0, 5)
	var mu sync.Mutex

	// 打印函数
	printState := func(timeMs int, producer, channel, consumer string) {
		fmt.Printf("%-6dms | %-15s | %-15s | %-25s\n", timeMs, producer, channel, consumer)
	}

	// 表头
	fmt.Printf("%-8s | %-15s | %-15s | %-25s\n", "时间", "生产者动作", "Channel状态", "消费者动作")
	fmt.Println("---------|-----------------|-----------------|---------------------------")

	var wg sync.WaitGroup

	// 生产者
	wg.Add(1)
	go func() {
		defer wg.Done()
		defer close(ch)

		for i := 1; i <= 10; i++ {
			elapsed := int(time.Since(startTime).Milliseconds())

			mu.Lock()
			channelState = append(channelState, i)
			channelStr := formatChannel(channelState)
			mu.Unlock()

			ch <- i

			if i == 1 {
				printState(elapsed, fmt.Sprintf("生产%d", i), channelStr, "开始读取")
			} else {
				printState(elapsed, fmt.Sprintf("生产%d", i), channelStr, "")
			}

			time.Sleep(100 * time.Millisecond)
		}
	}()

	// 消费者
	wg.Add(1)
	go func() {
		defer wg.Done()

		for num := range ch {
			// 开始消费
			elapsed := int(time.Since(startTime).Milliseconds())
			printState(elapsed, "", "", fmt.Sprintf("开始消费%d", num))

			// 消费时间
			time.Sleep(200 * time.Millisecond)

			// 消费完成
			elapsed = int(time.Since(startTime).Milliseconds())
			mu.Lock()
			if len(channelState) > 0 {
				channelState = channelState[1:]
			}
			channelStr := formatChannel(channelState)
			mu.Unlock()

			printState(elapsed, "", channelStr, fmt.Sprintf("消费%d完成", num))
		}
	}()

	wg.Wait()
}

func main() {
	// 运行简化版本
	simpleTimeline()

	time.Sleep(1 * time.Second)
}
